<script lang="ts" setup>
import TabContainer from './components/TabContainer.vue'
import NavigationBar from './components/NavigationBar.vue'
import type {ICategoryResponse} from '@/typings/api'
import {getCategoryList} from '@/api/common'
import ProductContainer from './components/ProductContainer.vue'

const {init, categoryState} = $(useCategory())

let categoryList = $ref<ICategoryResponse>()

// 请求课程分类接口
onLoad((options: any) => {
    // 拿到当前页面的参数重新赋值分类初始变量
    options.id && (categoryState.categoryId = Number(options.id));
    options.pid && (categoryState.categoryParentId = Number(options.pid));
    options.page && (categoryState.page = Number(options.page));
    options.size && (categoryState.size = Number(options.size));

    init({page: 1, size: 12})

    getCategoryList().then((res) => {
        categoryList = res.data
    })
})


// 页面是否可滑动
const overflowState = $ref('visible')

// 获取二级分类tab数据
const subCategory = $computed(() => {
    // 选中某个或者全部的分类tab
    return (
            (categoryState?.categoryParentId && categoryState.categoryParentId !== -1
                    ? categoryList
                            ?.filter(item => item.id === categoryState.categoryParentId)
                            .flatMap(item => item.subCategoryList)
                    : categoryList?.flatMap(item => item.subCategoryList)) || []
    )
})

// 下拉加载更多
onReachBottom(() => {
    uni.$emit('categoryLoadMore')
})
</script>

<template>
    <!-- 展开二级分类后页面不能滚动 -->
    <page-meta :page-style="`overflow: ${overflowState}`"/>

    <view style="background-color: #f3f3f3" overflow-x-hidden>
        <!-- 搜索框 -->
        <NavigationBar/>
        <!-- 分类导航栏 -->
        <TabContainer :category-list="categoryList || []"/>
        <ProductContainer :sub-category="subCategory"
                          @sync-overflow-state="(value: string) => (overflowState = value)"/>
    </view>
</template>
